<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/Home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>商品列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片区域 -->
        <el-card>
            <!-- 搜索框区域 -->
            <el-row :gutter="20">
                <el-col :span="8">
                      <el-input placeholder="请输入内容" v-model="goodsForm.query" clearable @clear="clearQuery">
                        <el-button slot="append" icon="el-icon-search" @click="queryGoods"></el-button>
                     </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="addGood">添加商品</el-button>
                </el-col>
            </el-row>
            <!-- 表格区域 -->
            <el-table :data="goodslist" border stripe>
                <el-table-column label="#" type="index"></el-table-column>
                <el-table-column label="商品名称" prop="goods_name"></el-table-column>
                <el-table-column label="商品价格(元)" prop="goods_price" width="95px"></el-table-column>
                <el-table-column label="商品重量" prop="goods_weight" width="70px"></el-table-column>
                <el-table-column label="创建时间" prop="add_time" width="140px">
                    <template slot-scope="scope">
                        {{scope.row.add_time|dateFormat}}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="120px">
                    <template slot-scope="scope">
                        <el-button type="primary" icon="el-icon-edit" size="mini" @click="editGood(scope.row.goods_id)"></el-button>
                        <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeGood(scope.row.goods_id)"></el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="goodsForm.pagenum"
                :page-sizes="[5, 10, 15, 20]"
                :page-size="goodsForm.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                background>
            </el-pagination>
        </el-card>
        <!-- 编辑商品信息对话框 -->
        <el-dialog
            title="编辑商品信息"
            :visible.sync="editDialogVisible"
            width="50%"
            @close="editGoodsDialogClosed"
            >
            <el-form :model="editGoodsForm" :rules="editGoodsFormRules" ref="editGoodsFormRef" label-width="100px" class="demo-ruleForm">
                <el-form-item label="商品名称" prop="goods_name">
                    <el-input v-model="editGoodsForm.goods_name"></el-input>
                </el-form-item>
                <el-form-item label="商品价格" prop="goods_price">
                    <el-input v-model.number="editGoodsForm.goods_price" type="number"></el-input>
                </el-form-item>                
                <el-form-item label="商品重量" prop="goods_weight">
                    <el-input v-model.number="editGoodsForm.goods_weight"></el-input>
                </el-form-item>                
                <el-form-item label="商品数量" prop="goods_number">
                    <el-input v-model.number="editGoodsForm.goods_number"></el-input>
                </el-form-item>
                <el-form-item label="商品介绍">
                    <el-input v-model="editGoodsForm.goods_introduce"></el-input>
                </el-form-item>
                <el-form-item label="商品图片">
                    <img :src="item.pics_big_url"  v-for="(item,i) in editGoodsForm.pics" :key="i">
                    <el-upload
                        class="upload-demo"
                        :action="uploadURL"
                        :on-preview="handlePreview"
                        :on-remove="handleRemove"
                        :headers="headers"
                        list-type="picture"
                        :on-success="uploadSuccess">
                        <el-button size="small" type="primary">点击上传</el-button>
                    </el-upload>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editGoodsConfirm">确 定</el-button>
            </span>
        </el-dialog>
                <!-- 图片预览对话框 -->
        <el-dialog
            title="图片预览"
            :visible.sync="pireviewVisible"
            width="50%"
        >
        <img :src="previewPath" alt="">
        </el-dialog>
    </div>
</template>

<script>
    export default {
        data(){
            var validategoods_num = (rule, value, callback) => {
                var msg=''
                switch(rule.fullField){
                    case 'goods_price':
                        msg='商品价格'
                        break
                    case 'goods_weight':
                        msg='商品重量'
                        break
                    case 'goods_number':
                        msg='商品数量'
                        break
                }
                if (value === '') {
                callback(new Error(`请输入${msg}`));
                } else if(typeof value !=='number'){
                    callback(new Error(`${msg}必须是大于0的整数或小数`));
                }else if (value <0 ) {
                callback(new Error(`${msg}必须是大于0的整数或小数`));
                } else {
                callback();
                }
            }
            return{
                //获取商品信息列表参数
                goodsForm:{
                    query:'',
                    pagesize: 10,
                    pagenum: 1
                },
                //总商品数据条数
                total:0,
                //商品信息数据
                goodslist:[],
                //修改商品信息的数据对象
                editGoodsForm:{},
                //控制编辑对话框的隐藏与出现
                editDialogVisible:false,
                //编辑对话框的验证规则对象
                editGoodsFormRules:{
                    goods_name:[
                        {required:true,message:"商品名称不能为空",tigger:'blur'}
                    ],
                    goods_price:[
                        {required:true,message:"商品价格不能为空"},
                        {validator:validategoods_num,tigger:'blur'}
                    ],
                    goods_weight:[
                        {required:true,message:"商品重量不能为空"},
                        {validator:validategoods_num,tigger:'blur'}
                    ],
                    goods_number:[
                        {required:true,message:"商品数量不能为空"},
                        {validator:validategoods_num,tigger:'blur'}
                    ],
                    goods_cat:[
                        {required:true,message:'请选择商品分类'}
                    ] 
                },
                //图片上传的后台路径
                uploadURL:"http://127.0.0.1:8888/api/private/v1/upload",
                //上传图片用的请求头
                headers:{
                    Authorization:sessionStorage.getItem('token')
                },
                //控制预览对话框的显示与隐藏
                pireviewVisible:false,
                //服务器响应图片的临时存放路径
                previewPath:'',
                //保存商品id
                goodsId:''
            }
        },
        created(){
            this.getGoodsList()
        },
        methods:{
            //获取所有商品信息
            async getGoodsList(){
                const {data:res}=await this.$http.get('goods',{params:this.goodsForm})
                if(res.meta.status!==200) return this.$message.error("获取商品信息失败")
                this.goodslist=res.data.goods
                this.total=res.data.total
                console.log(res.data.goods);
            },
            //控制每页显示几条数据
            handleSizeChange(newSize){
                console.log(newSize);
                this.goodsForm.pagesize=newSize
                this.getGoodsList()
            },
            //控制共有多少页
            handleCurrentChange(pageNum){
                console.log(pageNum);
                this.goodsForm.pagenum=pageNum
                this.getGoodsList()
            },
            //模糊查询
            queryGoods(){
                this.getGoodsList()
            },
            //清空查询所有数据展示
            clearQuery(){
                this.getGoodsList()
            },
            //跳转添加商品
            addGood(){
                this.$router.push('/goods/add')
            },
            //删除商品
            async removeGood(id){
                console.log(id);
                const confirmResult=await this.$confirm('此操作将永久删除该商品, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(err=>err)
                if(confirmResult!=='confirm') return this.$message.info('取消了此次删除')
                const {data:res}=await this.$http.delete(`goods/${id}`)
                if(res.meta.status!==200) return this.$message.error("删除商品信息失败")
                this.$message.success("删除商品信息成功")
                this.getGoodsList()
            },
            //编辑商品
            async editGood(id){
                console.log(id);
                this.goodsId=id
                const {data:res}=await this.$http.get(`goods/${id}`)
                if(res.meta.status!==200) return this.$message.error('根据id查询参数失败')
                console.log(res.data);
                this.editGoodsForm=res.data
                this.editDialogVisible=true
            },
            //图片展示
            handlePreview(file){
                console.log(file);
                this.previewPath=file.response.data.url
                this.pireviewVisible=true
            },
            //关闭图片预览框
            handleRemove(file){
                console.log(file);
                // 1.获取将要删除图片的临时存放路径
                var removeFile=file.response.data.tmp_path
                // 2.从pics这个数组中，找到这个图片的索引值
                var i=this.editGoodsForm.pics.findIndex(item=>{
                    return removeFile===item.pic
                })
                // 3.调用splice方法，把图片信息对象从pics数组中删除
                this.editGoodsForm.pics.splice(i,1)
            },
            //图片上传成功
            uploadSuccess(response){
                console.log(response);
                // 1.先拼接得到图片信息对象
                var picInfo={pic:response.data.tmp_path}
                //2.将图片信息对象push到addForm.pics中
                this.editGoodsForm.pics.push(picInfo)
            },
            //编辑对话框关闭重置表单数据为editGoodsForm绑定数据
            editGoodsDialogClosed(){
                this.$refs.editGoodsFormRef.resetFields()
            },
            //编辑完成
            editGoodsConfirm(){
                this.$refs.editGoodsFormRef.validate(async valid=>{
                    if(!valid) return
                    const {data:res}=await this.$http.put(`goods/${ this.goodsId}`,this.editGoodsForm)
                    if(res.meta.status!==200) return this.$message.error('编辑商品信息失败')
                    this.getGoodsList()
                    this.$message.success('编辑商品信息成功')
                    this.editDialogVisible=false
                })
            }
        }
    }
</script>

<style lang="less" scoped>
   
</style>